package com.elephant.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
       /* http.authorizeRequests()
                .antMatchers("/").permitAll() //允许所有访问
                .antMatchers("/main.html").hasRole("level1")
                .antMatchers("/emp/**").hasRole("level2")//限制访问添加员工页面
                .antMatchers("/emp*").hasRole("level2")//限制访问添加员工页面
                .antMatchers("/editEmp/*").hasRole("level1")//限制访问编辑
                .antMatchers("/deleEmp/*").hasRole("level2");//限制删除*/

        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
       // http.formLogin().loginPage("/");

        //开启自动配置的注销的功能
        // /logout 注销请求
        http.logout();
        // logoutSuccessUrl("/"); 注销成功来到首页
        http.logout().logoutSuccessUrl("/");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //在内存中定义，也可以在jdbc中去拿....
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("1")).roles("level1","level2")
                .and()
                .withUser("manager").password(new BCryptPasswordEncoder().encode("1")).roles("level1");

    }
}
